//
//  CertificationViewController.m
//  MyProject
//
//  Created by 石小强 on 2018/3/26.
//  Copyright © 2018年 yanjiaming. All rights reserved.
//

#import "CertificationViewController.h"
#import "CompanyInfoCertificateVC.h"
#import "JobCertificationViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "APAuthV2Info.h"
#import "DataSigner.h"
#import <ZMCert/ZMCert.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "JobCertificationViewController.h"


@interface CertificationViewController ()

@property (nonatomic, strong) UIScrollView *scrollV;
@property (nonatomic, strong) UIButton *backB;
@property (nonatomic, strong) UIButton *selectBtn;
@property (nonatomic, strong) UITextField *nameTextField;
@property (nonatomic, strong) UITextField *cardTextField;
@property (nonatomic, copy) NSString *authCode;

@end

@implementation CertificationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    
    [self setupSubViews];
}

//- (void)doBack:(id)sender {
//    [self dismissViewControllerAnimated:YES completion:nil];
//}

- (void)setupSubViews {
    _scrollV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    _scrollV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_scrollV];
    
    // 返回按钮
    UIButton *backB = [[UIButton alloc] initWithFrame:CGRectMake(0, STATUS_BAR_H, 44, 44)];
    [backB setImage:[UIImage imageNamed:@"ic_back_black"] forState:UIControlStateNormal];
    [backB addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.backB = backB;
    [self.view addSubview:backB];
    
    // 步骤
    UIFont *labelFont = [UIFont fontWithName:@"PingFangSC-Regular" size:12];
//    UIImageView *stepIV = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - 241) * 0.5, 45 + 10, 241, 31)];
    UIImageView *stepIV = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - 241) * 0.5, STATUS_BAR_H + 55 - 24, 241, 31)];
    stepIV.image = [UIImage imageNamed:@"buzhou"];
    [_scrollV addSubview:stepIV];
    CGSize positionSize = [Tool sizeWithText:@"实名认证" font:labelFont];
    UILabel *positionL = [[UILabel alloc] initWithFrame:CGRectMake((kScreenWidth - positionSize.width - 10) * 0.5, CGRectGetMaxY(stepIV.frame) + 16, positionSize.width + 10, 12)];
    positionL.text = @"实名认证";
    positionL.textColor = UIColorFromRGB(0x2AB4C2);
    positionL.font = labelFont;
    positionL.textAlignment = NSTextAlignmentCenter;
    [_scrollV addSubview:positionL];
    // 上传资料
    UILabel *uploadL = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(positionL.frame) + 50, positionL.mj_y, positionL.mj_w, positionL.mj_h)];
    uploadL.text = @"上传资料";
    uploadL.textColor = UIColorFromRGB(0x2B3033);
    uploadL.font = labelFont;
    [_scrollV addSubview:uploadL];
    // 实名认证
    UILabel *certificateL = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(positionL.frame) - 60 - positionSize.width, positionL.mj_y, positionL.mj_w, positionL.mj_h)];
    certificateL.text = @"职位认证";
    certificateL.textColor = UIColorFromRGB(0x2B3033);
    certificateL.font = labelFont;
    certificateL.textAlignment = NSTextAlignmentRight;
    [_scrollV addSubview:certificateL];
    
    // logo
    UIView *logoV = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(positionL.frame) + 18, kScreenWidth, 157)];
    logoV.backgroundColor = UIColorFromRGB(0xF9FCFF);
    [_scrollV addSubview:logoV];
    UIImageView *logoIV = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - 74) * 0.5, 50, 74, 88)];
    logoIV.image = [UIImage imageNamed:@"芝麻logo"];
    [logoV addSubview:logoIV];
    
    // centerLabel
    UIImageView *centerIV = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - 273) * 0.5, CGRectGetMaxY(logoV.frame), 273, 38)];
    centerIV.image = [UIImage imageNamed:@"certicate_top_two"];
    [_scrollV addSubview:centerIV];
    
    
    
    
    
    UIView *backView1 = [[UIView alloc]initWithFrame:CGRectMake(30, centerIV.mj_h + centerIV.mj_y + 30, kScreenWidth - 60, 50)];
    backView1.backgroundColor = UIColorFromRGB(0XE4ECF4);
    backView1.clipsToBounds = YES;
    backView1.layer.cornerRadius = 5;
    [_scrollV addSubview:backView1];
    
    UILabel *nameTitle = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 100, 50)];
    nameTitle.text = @"真实姓名";
    nameTitle.textColor = UIColorFromRGB(0x383F42);
    nameTitle.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    nameTitle.textAlignment = NSTextAlignmentLeft;
    [backView1 addSubview:nameTitle];
    
    self.nameTextField = [[UITextField alloc]initWithFrame:CGRectMake(nameTitle.mj_x+nameTitle.mj_w, 0, backView1.mj_w - nameTitle.mj_x  - nameTitle.mj_w - 15, 50)];
    self.nameTextField.placeholder = @"请填写身份证上的姓名";
    self.nameTextField.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    self.nameTextField.textAlignment = NSTextAlignmentRight;
    [backView1 addSubview:self.nameTextField];
    
    UIView *backView2 = [[UIView alloc]initWithFrame:CGRectMake(30, backView1.mj_h + backView1.mj_y + 15, kScreenWidth - 60, 50)];
    backView2.backgroundColor = UIColorFromRGB(0XE4ECF4);
    backView2.clipsToBounds = YES;
    backView2.layer.cornerRadius = 5;
    [_scrollV addSubview:backView2];
    
    UILabel *cardTitle = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 100, 50)];
    cardTitle.text = @"身份证号";
    cardTitle.textColor = UIColorFromRGB(0x383F42);
    cardTitle.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    cardTitle.textAlignment = NSTextAlignmentLeft;
    [backView2 addSubview:cardTitle];
    
    self.cardTextField = [[UITextField alloc]initWithFrame:CGRectMake(nameTitle.mj_x+nameTitle.mj_w, 0, backView2.mj_w - nameTitle.mj_x  - nameTitle.mj_w - 15, 50)];
    self.cardTextField.placeholder = @"请填写正确的身份证号";
    self.cardTextField.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    self.cardTextField.textAlignment = NSTextAlignmentRight;
    [backView2 addSubview:self.cardTextField];
    
    UILabel *desTitle = [[UILabel alloc] initWithFrame:CGRectMake(15, backView2.mj_h + backView2.mj_y + 15, kScreenWidth - 30, 15)];
    desTitle.text = @"*请您如实填写本人信息，否则驳回认证";
    desTitle.textColor = UIColorFromRGB(0xAFB8BC);
    desTitle.font = labelFont;
    desTitle.textAlignment = NSTextAlignmentCenter;
    [_scrollV addSubview:desTitle];
    
//    //
    CGFloat jumpBtnY = [Tool isIphoneX] ? kScreenHeight - 49 - 34 : kScreenHeight - 49;
    UIButton *jumpBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, jumpBtnY, kScreenWidth, 49)];
    [jumpBtn setBackgroundColor:UIColorFromRGB(0x00BCCC)];
    [jumpBtn setTitle:@"提交" forState:UIControlStateNormal];
    jumpBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    [jumpBtn addTarget:self action:@selector(jumpBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:jumpBtn];
//
//    UIButton *selectBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(jumpBtn.frame), kScreenWidth, 66)];
//    [selectBtn setImage:[UIImage imageNamed:@"ic_Unchecked"] forState:UIControlStateNormal];
//    [selectBtn setImage:[UIImage imageNamed:@"ic_selected"] forState:UIControlStateSelected];
//    [selectBtn addTarget:self action:@selector(selectBtnClick) forControlEvents:UIControlEventTouchUpInside];
//    [selectBtn setTitle:@"在职同事认证说明" forState:UIControlStateNormal];
//    [selectBtn setTitleColor:UIColorFromRGB(0x86A4AE) forState:UIControlStateNormal];
//    [selectBtn.titleLabel setFont:[UIFont fontWithName:@"PingFangSC-Regular" size:12]];
//    selectBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
//    self.selectBtn = selectBtn;
//    [_scrollV addSubview:selectBtn];
    
    
    

    
    
//    UIImageView *bottomIV = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - 345) * 0.5, CGRectGetMaxY(selectBtn.frame) + 76, 345, 148)];
//    bottomIV.image = [UIImage imageNamed:@"certicate_bottom"];
//    [_scrollV addSubview:bottomIV];
    
    _scrollV.contentSize = CGSizeMake(0, desTitle.mj_y +desTitle.mj_h + 60);
    _scrollV.showsVerticalScrollIndicator = NO;
}

- (void)backBtnClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)jumpBtnClick {
    if (self.nameTextField.text.length == 0) {
        ALERT_VIEW(@"请输入姓名");
        return;
    }else if (self.cardTextField.text.length == 0) {
        ALERT_VIEW(@"请输入您的身份证号");
        return;
    }
    __weak typeof(self) weakSelf = self;
    [self showProgressWithView:self.view animated:YES];
    [YJMSendRequest postDataWithParameters:@{@"certName":self.nameTextField.text,@"certNo":self.cardTextField.text} url:@"common/initAntAuthenticate" result:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        [self hideProgress:self.view animated:YES];
        if([result[@"result"] integerValue] == 1)
        {
            ZMCertification *manager = [[ZMCertification alloc] init];
            
            //  不进行动作检测视频录制
            [manager startWithBizNO:result[@"data"][@"bizNo"]
                         merchantID:result[@"data"][@"pid"]
                          extParams:nil
                     viewController:self
                           onFinish:^(BOOL isCanceled, BOOL isPassed, ZMStatusErrorType errorCode) {
                               if (isCanceled) {
                            
                                   ALERT_VIEW(@"用户取消了认证");
                               }else{
                                   if (isPassed) {
                                       NSLog(@"认证成功");
//                                       ALERT_VIEW(@"认证成功，应该要进入上传资料页面了");
                                       
                                       JobCertificationViewController *job = [[JobCertificationViewController alloc] init];
                                       job.params = self.params;
                                       job.name = self.nameTextField.text;
                                       job.companyName = self.companyName;
                                       job.jobName = self.jobName;
                                       job.regionName = self.regionName;
                                       job.minTime = self.minTime;
                                       job.maxTime = self.maxTime;
                                       job.index = self.index;
                                       [self.navigationController pushViewController:job animated:YES];
                                   }else{
                                       ALERT_VIEW(@"认证失败了");
                                   }
                               }
                           }];
            
        }else{
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
        
    }];
    
//    NSString *pid = @"2088031625543443";
//    NSString *appID = @"2018032702457597";
//    NSString *privateKey = @"MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCbkoD3Kn1QHsvJOoygddu5gyAvCVRH3GnBli8xq9EXMqApZjuZwCixgAFAATRpcL6bgDqOtQz0SEitDVR9r4DHejYxxq+/rTIMu+6cwQp7PDAWdSvTod00EDhiBU4cDUsgqQRaHIKDhOn5S2IRj3XqttN16soYmOklUYLkan7nWq25EZzdANqyS7LDjMwMBr15RrWg1q3sbKDeL/49y3Qob3dV1ZGDiSwE9quWhKikRsUfym6Zlmqe1HkqtgbGUH0S1JITgr3XGgMJjqEf/drH/X/+vl3h1vGUl4A6dUNpNvmk/yKhmVXyQ1a7BRjghAZMPBOcQUxt6Hy70vzxReATAgMBAAECggEAdAvGc5iYPUmbjZFFEPSZYDo1qaB149zAbo0Oyyh1Ia671eXSk4/JSw5G4G2FoRletTPjekwHS7kXrS6CVfayQxogjuS8eGhDK0iMZxWAMgjlffsNJCJblNh8lnGKoFYyMjyhaG5X1K8ysKjQkHTI6rpR5mWrNsnpL9MrpiLiYsQRbJob+3T2Vnvj/BTqz/XCGO/J3Jte+fOImBhl5uH7eF1A+8LWrnlRc+VNWgXgzCs9OgsKYnlvQNR+BmJs3qG8oStNdpMI3GbArzR1LPH+weom9Dmna8n5q/x0whfx3iD5TmJ75NTZuAGjZd1kjAyKBWDIcAp9zuwwchaMBD3XcQKBgQDOD1IOvv+blQAllPOj8vC39PMusOqU8OnNSKiOpBZrB0KM7Z0UvzyObGKB00KakxF5VAqYrtt3I7SzB3Q/BiKkmsWBhQbye9tVfEoAxgSvcYwXf3FG2253Y82fU8lOXa3wv/zm74i0cgB91scARVhB753kTXYb/A3ssZO7SJiHrQKBgQDBRsGy+aWdxoMEEKvTb/Wd4Sbyx3e9qz2a9OeUzjXt5abRfwWlvfvd0puNAE+qfzL2tCbJTz5yBL7GnWprt0NZ6i/v7BoqL1+/QINu24hvjRE0ub09iddfNiEbbFmNmXSH6H9YqG+ht2rJBD62Pk7/vwAUgz1GtCO7ljUri6f+vwKBgAbN0rPR8ra8cMjM5k6fkvtAB1efV9+bJN02bPpoyKS4FKZ6ohkxR1qckZQf2a8o9AbBk6f+/hgtAaZ3tIrwNOyif6sLLXOMS23DMN5dq4HvieSsvJzOWhNvJDcCmT8RMNEmRb+KYUU0DngZQ3Dq2UM0Gk6TkDbUV9Fc+7fPadnxAoGAaG5l7OGtVhHT6tdjMEy3ZwYn+FhE38vt7pNTqfi99Pv4Zgv/Li34MERC3i4D3bj6/YgbyPwzXoIn3sNhpDASiTvbiQSGorKURo+CNN0T3EpZuKZ/lQeswnpJ6zphLPx0lZbPcEUahEPJxDGx/OCv6Mn4Lh03d8OP5yTjN9MvA5sCgYAweO3//IQJKt1qQm/c2AND/F2gxFFOMAJkfhrgKZAIIoxnxPdwW/KDFrIdTJONZx+lO7LRz14pU32Xw1PYrrsxvlAOO3smin81GG+HiRTiZ0OGNKP8g7l50z/yzuiNUhfNQw5THj60WKl1syMKu6GCm1BVzSZqqdUQ3FDI+4jogA==";
//    /*============================================================================*/
//
//    //pid和appID获取失败,提示
//    if ([pid length] == 0 ||
//        [appID length] == 0 ||
//        [privateKey length] == 0)
//    {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
//                                                        message:@"缺少pid或者appID或者私钥。"
//                                                       delegate:self
//                                              cancelButtonTitle:@"确定"
//                                              otherButtonTitles:nil];
//        [alert show];
//        return;
//    }
//
//    //生成 auth info 对象
//    APAuthV2Info *authInfo = [APAuthV2Info new];
//    authInfo.pid = pid;
//    authInfo.appID = appID;
//
//    //auth type
//    NSString *authType = [[NSUserDefaults standardUserDefaults] objectForKey:@"authType"];
//    if (authType) {
//        authInfo.authType = authType;
//    }
//
//    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
//    NSString *appScheme = @"taijieAlipay";
//
//    // 将授权信息拼接成字符串
//    NSString *authInfoStr = [authInfo description];
//    NSLog(@"authInfoStr = %@",authInfoStr);
//
//    // 获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
//    id<DataSigner> signer = CreateRSADataSigner(privateKey);
//    NSString *signedString = [signer signString:authInfoStr];
//
//    // 将签名成功字符串格式化为订单字符串,请严格按照该格式
//    if (signedString.length > 0) {
//        authInfoStr = [NSString stringWithFormat:@"%@&sign=%@&sign_type=%@", authInfoStr, signedString, @"RSA"];
//        WS(weakSelf)
//        [[AlipaySDK defaultService] auth_V2WithInfo:authInfoStr
//                                         fromScheme:appScheme
//                                           callback:^(NSDictionary *resultDic) {
//                                               NSLog(@"result = %@",resultDic);
//                                               // 解析 auth code
//                                               NSString *result = resultDic[@"result"];
//                                               NSString *authCode = nil;
//                                               if (result.length>0) {
//                                                   NSArray *resultArr = [result componentsSeparatedByString:@"&"];
//                                                   for (NSString *subResult in resultArr) {
//                                                       if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
//                                                           authCode = [subResult substringFromIndex:10];
//                                                           break;
//                                                       }
//                                                   }
//                                               }
//                                               NSLog(@"授权结果 authCode = %@", authCode?:@"");
//
//                                               weakSelf.authCode = authCode;
//                                               /**把这个接口给后台换取结果即可*/
//                                               [weakSelf getZMScore];
//                                           }];
//    }
}

- (void)getZMScore {
    WS(weakSelf)
    [self showProgressWithView:self.view animated:YES];
    [SendRequest getZmScoreByToken:self.authCode result:^(NSDictionary *result, NSError *error) {
        [weakSelf hideProgress:self.view animated:YES];
        result = [CommonUtils decryptDicWithResult:result];
        if([result[@"result"] integerValue] == 1) {
            SaintiLog(@"获取芝麻分成功 = %@", [result objectForKey:@"data"]);
            [[NSUserDefaults standardUserDefaults] setValue:[result objectForKey:@"data"] forKey:@"zhimaScore"];
            [[NSUserDefaults standardUserDefaults] synchronize];

            CompanyInfoCertificateVC *companyVC = [[CompanyInfoCertificateVC alloc] init];
            [weakSelf.navigationController pushViewController:companyVC animated:YES];
        } else {
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
    }];
}

- (void)selectBtnClick {
    self.selectBtn.selected = !self.selectBtn.selected;
}

- (IBAction)zhimaBtnClick:(id)sender {
    JobCertificationViewController *jobCVC = [[JobCertificationViewController alloc] init];
    [self.navigationController pushViewController:jobCVC animated:YES];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}

@end
